package com.database;

import java.util.ArrayList;

import com.model.Notebook;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class NotebookAdapter {
	private static final String DATABASE_NAME = "springpadapp";
	private static final int DATABASE_VERSION = 1;
	private SQLiteDatabase db;
	private DbHelper dbHelper;
	private Context ctx;
	
	
	public static final String TABLE_NAME1="notebook";
	public static final String KEY_ROWID = "_id";
	private static final String KEY_NAME="name";
	private static final String KEY_ITEM="item";
	public NotebookAdapter(Context ctx){
		this.ctx=ctx;
	}
	public NotebookAdapter open(){
		dbHelper = new DbHelper(ctx, DATABASE_NAME, null, DATABASE_VERSION);
		db=dbHelper.getWritableDatabase();
		return this;
	}
	public void close(){
		dbHelper.close();
	}
	public long createNoteBook(Notebook gp){
		Log.d("NoteBook","creating a new notebook");
		ContentValues initialValues = new ContentValues();
	    initialValues.put(KEY_NAME, gp.getName());
	    initialValues.put(KEY_ITEM, gp.getItems());
	    return db.insert(TABLE_NAME1, null, initialValues);
	}
	public Cursor fetchAllGroups(){
		String colNames[]={KEY_ROWID,KEY_NAME};
		dbHelper.onCreate(db);
		return db.query(TABLE_NAME1, colNames, null, null, null, null, null);
	}
	public boolean deleteGroup(long _id){
		return db.delete(TABLE_NAME1, KEY_ROWID+ '=' +_id, null)>0;
	}
	public ArrayList<Notebook> fetchGroups(){
		ArrayList<Notebook> list=new ArrayList<Notebook>();
		Cursor c=fetchAllGroups();
		if(c!=null){
			while(c.moveToNext()){
				int id=c.getInt(c.getColumnIndexOrThrow(KEY_ROWID));
				String name=c.getString(c.getColumnIndexOrThrow(KEY_NAME));
				Notebook g=new Notebook(name,id);
				list.add(g);
			}
		}
		return list;
	}
}
